package sk.xorty.quartz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.File;
import java.io.IOException;

@Component("fileReplicator")
public class FileReplicatorImpl implements FileReplicator {

    @Value("#{pathProps.src}")
    private String srcDir;

    @Value("#{pathProps.dest}")
    private String destDir;

    @Autowired FileCopier fileCopier;

    @Override
    public String getSrcDir() {
        return srcDir;
    }

    @Override
    public void setSrcDir(String srcDir) {
        this.srcDir = srcDir;
        revalueateDirectories();
    }

    @Override
    public String getDestDir() {
        return destDir;
    }

    @Override
    public void setDestDir(String destDir) {
        this.destDir = destDir;
        revalueateDirectories();
    }

    @Override
    public void replicate() throws IOException {
        System.out.println("Replicating started ...");
        File[] files = new File(srcDir).listFiles();

        Assert.notNull(files);
        for (File file : files) {
            if (file.isFile()) {
                fileCopier.copyFile(srcDir, destDir, file.getName());
            }
        }

    }

    private void revalueateDirectories() {
        File src = new File(srcDir);
        File dest = new File(destDir);

        if (!src.exists()) {
            src.mkdirs();
        }

        if (!dest.exists()) {
            dest.mkdirs();
        }
    }
}
